package com.controller.sys;


import com.common.Result;
import com.common.log.OperationLog;
import com.common.log.OperationType;
import com.entity.sys.Role;
import com.entity.sys.User;
import com.service.sys.UserService;
import com.service.sys.UserVoService;
import com.vo.sys.NewPassParam;
import com.vo.sys.UserVo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.regex.Pattern;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author clay
 * @since 2022-02-15
 */
@Api("UserController")
@RestController
@RequestMapping("/user")
public class UserController {

    @Resource
    private UserService userService;

    @Resource
    private UserVoService userVoService;

    @ApiOperation("添加用户")
    @OperationLog(operationType = OperationType.INSERT, describe = "添加用户信息", entity = User.class, primaryKey = "id")
    @PostMapping("/add")
    public Result add(@RequestBody User user) throws ParseException {
        //给昵称赋值,防止聊天页面没有昵称
        user.setNickname(user.getRealName());
        //获取当前的年月日
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        String nowDateStr = format.format(new Date());
        //String的日期转为Date类型
        Date nowDate = format.parse(nowDateStr);
        //处理user中的其他日期
        //校验是否成年
        Date birthday = format.parse(user.getAge());
        //校验所输入生日是否在在当前日期之前
        if (birthday.before(nowDate)) {
            //校验是否成年
            if (nowDate.getYear() - birthday.getYear() < 18) {
                return Result.fail("当前人员未满18岁！");
            }
        }
        //校验合同起始日期与终止日期前后关系
        //起始日期
        Date startDate = format.parse(user.getBeginContract());
        //终止日期
        Date endDate = format.parse(user.getEndContract());
        //校验起始日期是否在终止日期之后
        if (startDate.after(endDate)) {
            return Result.fail("合同起始日期不能在终止日期之后！");
        }
        //校验身份证号上的日期是否与输入的生日一致
        //截取身份证号生日部分
        String idCardBir = user.getNbr().substring(6, 14);

        StringBuilder idCardBirthFormat = new StringBuilder(idCardBir.substring(0, 4))
                .append("-")
                .append(idCardBir.substring(4, 6))
                .append("-")
                .append(idCardBir.substring(6, 8));
        Date idCardBirthDate = format.parse(idCardBirthFormat.toString());
        if (!idCardBirthDate.equals(birthday)) {
            return Result.fail("身份证号上的日期与输入的生日不一致！");
        }
        //正则表达式校验手机号
        String regex = "^((13[0-9])|(14[5,7])|(15[0-3,5-9])|(17[0,3,5-8])|(18[0-9])|166|198|199|(147))\\d{8}$";
        Pattern pattern = Pattern.compile(regex);
        if (!pattern.matcher(user.getPhone()).matches()){
            return Result.fail("手机号格式不正确！");
        }
        //正则表达式校验身份证号
        String idCardRegex = "^[1-9]\\d{5}[1-9]\\d{3}((0\\d)|(1[0-2]))(([0|1|2]\\d)|3[0-1])\\d{3}([0-9]|X)$";
        Pattern idCardPattern = Pattern.compile(idCardRegex);

        //正则表达式邮箱验证
        String emailRegex = "^[a-zA-Z0-9_-]+@[a-zA-Z0-9_-]+(\\.[a-zA-Z0-9_-]+)+$";
        if (!idCardPattern.matcher(user.getNbr()).matches()){
            return Result.fail("身份证号格式不正确！");
        }
        return Result.success(userService.addUser(user));
    }

    @ApiOperation("查询用户")
    @PostMapping("/select")
    public Result select(@RequestBody User user) {
        return Result.success(userService.selectUser(user));
    }

    @ApiOperation("修改用户信息")
    @OperationLog(operationType = OperationType.UPDATE, describe = "修改权限信息", entity = UserVo.class, primaryKey = "id")
    @PostMapping("/update")
    public Result update(@RequestBody UserVo userVo) throws ParseException {
        //给昵称赋值,防止聊天页面没有昵称
        userVo.setNickname(userVo.getRealName());
        //获取当前的年月日
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        String nowDateStr = format.format(new Date());
        //String的日期转为Date类型
        Date nowDate = format.parse(nowDateStr);
        //处理user中的其他日期
        //校验是否成年
        Date birthday = format.parse(userVo.getAge());
        //校验所输入生日是否在在当前日期之前
        if (birthday.before(nowDate)) {
            //校验是否成年
            if (nowDate.getYear() - birthday.getYear() < 18) {
                return Result.fail("当前人员未满18岁！");
            }
        }
        //校验身份证号上的日期是否与输入的生日一致
        //截取身份证号生日部分
        String idCardBir = userVo.getNbr().substring(6, 14);
        StringBuilder idCardBirthFormat = new StringBuilder(idCardBir.substring(0, 4))
                .append("-")
                .append(idCardBir.substring(4, 6))
                .append("-")
                .append(idCardBir.substring(6, 8));
        Date idCardBirthDate = format.parse(idCardBirthFormat.toString());
        if (!idCardBirthDate.equals(birthday)) {
            return Result.fail("身份证号上的日期与输入的生日不一致！");
        }

        //校验合同起始日期与终止日期前后关系
        //起始日期
        Date startDate = format.parse(userVo.getBeginContract());
        //终止日期
        Date endDate = format.parse(userVo.getEndContract());
        //校验起始日期是否在终止日期之后
        if (startDate.after(endDate)) {
            return Result.fail("合同起始日期不能在终止日期之后！");
        }
        //正则表达式校验手机号
        String regex = "^((13[0-9])|(14[5,7])|(15[0-3,5-9])|(17[0,3,5-8])|(18[0-9])|166|198|199|(147))\\d{8}$";
        Pattern pattern = Pattern.compile(regex);
        if (!pattern.matcher(userVo.getPhone()).matches()){
            return Result.fail("手机号格式不正确！");
        }
        //正则表达式校验身份证号
        String idCardRegex = "^[1-9]\\d{5}[1-9]\\d{3}((0\\d)|(1[0-2]))(([0|1|2]\\d)|3[0-1])\\d{3}([0-9]|X)$";
        Pattern idCardPattern = Pattern.compile(idCardRegex);
        if (!idCardPattern.matcher(userVo.getNbr()).matches()){
            return Result.fail("身份证号格式不正确！");
        }


        if (userVoService.updateByPrimary(userVo)) {
            return Result.success("操作成功");
        }
        return Result.fail("修改失败!");
    }

    @ApiOperation("删除用户")
    @OperationLog(operationType = OperationType.DELETE, describe = "删除权限信息", entity = Role.class, primaryKey = "id")
    @GetMapping("/delete/{id}")
    public Result delete(@PathVariable String id) {
//        if (userService.deleteById(id)) {
//            return Result.success("操作成功");
//        }
        return Result.fail("无法删除!");
    }

    @ApiOperation("通过id查询用户信息")
    @GetMapping("/getUserById/{id}")
    public Result getUserById(@PathVariable String id) {
//        if (userService.deleteById(id)) {
//            return Result.success("操作成功");
//        }
        User user = userService.getById(id);
        user.setPassword(null);
        return Result.success(user);
    }

    @ApiOperation("重置用户密码")
    @OperationLog(operationType = OperationType.UPDATE, describe = "重置密码信息", entity = UserVo.class, primaryKey = "id")
    @GetMapping("/resetPassword/{id}")
    public Result resetPassword(@PathVariable String id) {
        return Result.success(userService.resetPassword(id));
    }

    @ApiOperation("修改密码")
    @OperationLog(operationType = OperationType.UPDATE, describe = "修改密码信息", entity = NewPassParam.class, primaryKey = "id")
    @RequestMapping("/updatePassword")
    public Result updatePassword(@RequestBody NewPassParam newPasswordParam) {
        //后端校验两次密码是否一致
        if (!newPasswordParam.getPass().equals(newPasswordParam.getCheckPass())) {
            return Result.fail("两次密码不一致！！！");
        }
        //调用修改密码的方法
        Boolean changePassword = userVoService.changePassword(newPasswordParam);

        if ("true".equals(changePassword.toString())) {
            return Result.success(changePassword);
        } else {
            return Result.fail(400, "密码修改失败，请再次尝试");
        }
    }
}
